package com.sfang.common.base.http.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import com.sfang.common.base.http.Interceptor.BodyReaderRequestWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author xuzilou
 * @date 2021/3/24 17:26
 */
@Component
@Order(1)
@Slf4j
@WebFilter(filterName = "bodyReader", urlPatterns = "/**")
public class BodyReaderFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("BodyReaderFilter init");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        String contentType = req.getContentType();
        if (StrUtil.isNotBlank(contentType) && contentType.contains(ContentType.JSON.toString())) {
            BodyReaderRequestWrapper requestWrapper = new BodyReaderRequestWrapper(req);
            filterChain.doFilter(requestWrapper, servletResponse);
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}
